<template>
	<view>
		<view class="uni-header">
			<view class="uni-group">
				<button class="uni-button" type="default" size="mini" @click="navigateTo('./add',true)">新增主分类</button>
				<button class="uni-button" type="default" size="mini" @click="navigateTo('./list')">列表分类</button>
				<button class="uni-button" type="default" size="mini" @click="sorts()">主分类排序</button>
				<text class="margin-left-sm text-red">点击大分类，对子分类排序</text>
			</view>
		</view>
		<view class="uni-container">
			<ly-tree :tree-data="treeData" :ready="ready" :props="props" node-key="_id" highlightCurrent showNodeIcon
				:expandOnClickNode="false" :showActions="true" @node-expand="handleNodeExpand"
				@node-click="handleNodeClick" @node-extbutton-click="handleNodeExtButtonClick">
			</ly-tree>
		</view>

		<uni-popup ref="sortPopup" type="dialog">
			<view class="bg-white padding radius order-dialog">
				<view class="title margin-bottom-sm">
					<text>分类排序</text>
				</view>
				<view class="fields flex">
					<scroll-view scroll-y="true" class="scroll-Y">
						<view v-for="(item,index) in sortData" :key="index"
							class="flex margin-bottom-sm justify-between">
							<view class="">
								<text>{{item.posid}}</text>
								<text class="margin-left-sm">{{item.name}}</text>
							</view>
							<view class="">
								<button class="uni-button" type="default" size="mini" @click="moveUp(true,index)"
									:disabled="index==0">上1</button>
								<button class="uni-button" type="default" size="mini" @click="moveUp(true,index,5)"
									:disabled="index==0">上5</button>
								<button class="uni-button" type="default" size="mini" @click="moveUp(false,index)"
									:disabled="index == sortData.length-1">下1</button>
								<button class="uni-button" type="default" size="mini" @click="moveUp(false,index,5)"
									:disabled="index == sortData.length-1">下5</button>
							</view>
						</view>
					</scroll-view>
				</view>
				<view class="uni-button-group margin-top-sm">
					<button type="primary" class="uni-button" @click="submitSort">提交</button>
					<button @click="closePop('sortPopup')" class="uni-button">关闭</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	const db = uniCloud.database()
	const cmd = db.command;
	const dbCollectionName = 'cloud_goods_categories'
	import {
		mapState,
	} from 'vuex'
	export default {
		data() {
			return {
				query: '',
				where: '',
				sortData: [],
				treeData: [],
				ready: false, // 这里用于自主控制LyTree 的 loading加载状态，避免异步正在加载数据的空档显示“暂无数据”
				props: function() {
					return {
						// 这里的label就可以使用函数进行自定义的渲染了
						label(data, node) {
							return [
								(node.data.posid + " - ") + node.data.name,
								node.data.id,
								node.data.src,
								node.data.isShow ? '已启用' : '未启用'
							]
						},
						//label: 'name', // 指把数据中的‘personName’当做label也就是节点名称
						icon(data, node) {
							if (node.data.parent_id == "") {
								return ""
							}
						}
					}
				},
			}
		},
		onLoad() {
			this.loadData()
		},
		computed: {
			...mapState('app', ['adminShop'])
		},
		methods: {
			loadData() {
				var that = this
				db.collection(dbCollectionName).where(`shopid==${this.adminShop.id}`)
					.field("posid,name,id,pid,parent_id,src,isShow,shopid")
					.orderBy("parent_id asc,posid asc")
					.get({
						getTree: true
					})
					.then((res) => {
						that.treeData = res.result.data
						console.log("treeData", res.result.data);
					}).catch((err) => {
						uni.showModal({
							content: err.message || '请求服务失败',
							showCancel: false
						})
					}).finally(() => {
						that.ready = true // 关闭tree控件的等待loading
					})
			},
			navigateTo(url, clear) {
				// clear 表示刷新是否自动刷新，true 表示刷新
				uni.navigateTo({
					url,
					events: {
						refreshData: () => {
							if (clear) {
								this.loadData()
							}
						}
					}
				})
			},
			// 多选处理
			selectedItems() {
				// var dataList = this.$refs.udb.dataList
				// return this.selectedIndexs.map(i => dataList[i]._id)
			},
			//批量删除
			delTable() {
				// this.$refs.udb.remove(this.selectedItems())
			},
			// 多选
			selectionChange(e) {
				// this.selectedIndexs = e.detail.index
			},
			confirmDelete(id) {
				// this.$refs.udb.remove(id)
			},
			handleNodeClick(obj) { // 点主节点文字，进入修改页面
				console.log('handleNodeClick', JSON.stringify(obj));
				this.sorts(obj)
				//this.navigateTo('./edit?id=' + obj.data._id, true)
			},
			handleNodeExpand(obj) {
				// console.log('handleNodeExpand', JSON.stringify(obj));
			},
			handleNodeExtButtonClick(obj) {
				var that = this
				// console.log('handleNodeExtButtonClick', JSON.stringify(obj));
				switch (obj.buttonvalue) {
					case "del": //删除
						uni.showModal({
							content: "确认删除？",
							success(res) {
								if (res.confirm) {
									db.collection(dbCollectionName).where(cmd.or({
											_id: obj.data._id
										}, {
											parent_id: obj.data._id
										})).remove()
										.then((res) => {
											that.loadData()
										})
										.catch((err) => {
											console.log(err.message)
										})
										.finally(() => {

										})
								}
							}
						})

						break;
					case "newchildren": // 新增子女
						this.navigateTo('./add?parent_id=' + obj.data.menu_id + '&pid=' + obj.data._id + '&parent_name=' +
							obj.data.name,
							true)
						break;
					case "edit": // 修改
						this.navigateTo('./edit?id=' + obj.data._id, true)
						break;
					default:
						break;
				}
			},
			closePop(name) {
				this.$refs[name].close();
			},
			sorts(obj) {
				if (!obj) {
					this.sortData = this.treeData.map(e => {
						return {
							_id: e._id,
							name: e.name,
							posid: e.posid
						}
					});
				} else if (obj.data.children && obj.data.children.length > 0) {
					this.sortData = obj.data.children.map(e => {
						return {
							_id: e._id,
							name: e.name,
							posid: e.posid
						}
					});
				} else {
					return false;
				}
				this.$refs.sortPopup.open()
			},
			moveUp(isUp, index, length = 1) {
				for (let i = 0; i < length; i++) {
					let oldIndex = isUp ? index - 1 : index + 1;
					if (oldIndex > -1 && oldIndex < this.sortData.length) {
						let tmp = this.sortData[oldIndex];
						this.sortData[oldIndex] = this.sortData[index];
						this.$set(this.sortData, index, tmp);
						index = oldIndex;
					}
				}
				console.log(this.sortData)
			},
			submitSort() {
				let index = 1;
				uni.showLoading({
					title: "处理中",
					mask: true
				})
				for (let item of this.sortData) {
					db.collection(dbCollectionName).doc(item._id).update({
						posid: index
					})
					index++;
				}
				setTimeout(() => {
					this.$refs.sortPopup.close()
					this.loadData(true);
					uni.showToast({
						title: "排序成功"
					})
				}, 2000)
			}
		}
	}
</script>


<style lang="scss">
	.order-dialog {
		min-width: 1200rpx;
	}

	.fields {
		max-height: 1000rpx;
	}
</style>
